<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getDirListApi, getSubDirListApi, deleteDirApi } from "@/api/clusters/distributeFiles";
import type { FileInfoModel } from "@/api/clusters/distributeFiles";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

// 服务器标识 我们只部署一个服务器后台 那么则默认为server1
const serverKey = ref<string>('server1');

// 选中的文件/目录项
const selectedItems = ref<FileInfoModel[]>([]);

// 当前路径
const currentPath = ref<string>('');

// 路径导航记录
const pathHistory = ref<Array<{ name: string; path: string }>>([]);

// 文件/目录列表数据
const fileList = ref<FileInfoModel[]>([]);
const loading = ref(false);

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return `${bytes} B`;
  else if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
  else if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(2)} MB`;
  else return `${(bytes / 1073741824).toFixed(2)} GB`;
};

import { computed } from 'vue';

// 加载目录列表
const loadDirList = async (path: string = '') => {
  try {
    if (!serverKey.value.trim()) {
      ElMessage.warning(t('clusters.distributeFilePage.selectServerKey'));
      return;
    }

    loading.value = true;
    // 清空选中项
    selectedItems.value = [];
    let response;

    if (path === '') {
      // 获取根目录列表
      response = await getDirListApi(serverKey.value);
      pathHistory.value = [];
      currentPath.value = '';
    } else {
      // 获取子目录列表
      response = await getSubDirListApi(serverKey.value, path);
      currentPath.value = path;
    }

    if (response.code === 0) {
      fileList.value = response.data.list || [];
    } else {
      ElMessage.error(response.message || t('clusters.distributeFilePage.getDirFail'));
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
    ElMessage.error(t('clusters.distributeFilePage.getDirFail'));
    console.error('Failed to load directory list:', error);
  }
};

// 进入子目录
const enterSubDir = (item: FileInfoModel) => {
  if (item.isDir) {
    // 记录路径历史
    pathHistory.value.push({
      name: item.name,
      path: currentPath.value
    });
    // 加载子目录
    loadDirList(item.path);
  }
};

// 返回上级目录
const goBack = () => {
  if (pathHistory.value.length > 0) {
    const lastPath = pathHistory.value.pop()!;
    loadDirList(lastPath.path);
  } else {
    loadDirList(''); // 返回根目录
  }
};

// 获取项目类型文本
const getItemTypeText = (isDir: boolean) => {
  return t(`clusters.distributeFilePage.${isDir ? 'directory' : 'file'}`);
};

// 删除单个文件/目录
const handleDelete = async (item: FileInfoModel) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      t('clusters.distributeFilePage.confirmDeleteSingleMsg', {
        itemType: getItemTypeText(item.isDir),
        name: item.name
      }),
      t('clusters.distributeFilePage.confirmDelete'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning',
      }
    );

    if (confirmResult === 'confirm') {
      const response = await deleteDirApi(serverKey.value, item.path);
      if (response.code === 0 && response.data.success) {
        ElMessage.success(t('clusters.distributeFilePage.deleteSuccess', {
          itemType: getItemTypeText(item.isDir)
        }));
        // 从选中项中移除已删除的项
        const index = selectedItems.value.findIndex(i => i.path === item.path);
        if (index > -1) {
          selectedItems.value.splice(index, 1);
        }
        await loadDirList(currentPath.value);
      } else {
        ElMessage.error(response.message || t('clusters.distributeFilePage.deleteFail'));
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('clusters.distributeFilePage.deleteFailedMsg'));
      console.error('Failed to delete file/directory:', error);
    }
  }
};

// 批量删除文件/目录
const handleBatchDelete = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning(t('common.selectAtLeastOne'));
    return;
  }

  try {
    // 判断是否全部是目录或文件
    const allAreDirs = selectedItems.value.every(item => item.isDir);
    const allAreFiles = selectedItems.value.every(item => !item.isDir);
    let itemType;

    if (allAreDirs) {
      itemType = t('clusters.distributeFilePage.directory');
    } else if (allAreFiles) {
      itemType = t('clusters.distributeFilePage.file');
    } else {
      itemType = t('common.items');
    }

    const confirmResult = await ElMessageBox.confirm(
      t('clusters.distributeFilePage.confirmDeleteMsg', {
        count: selectedItems.value.length,
        itemType: itemType
      }),
      t('clusters.distributeFilePage.confirmDelete'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning',
        showCancelButton: true,
        danger: true,
        title: t('clusters.distributeFilePage.deleteWarning')
      }
    );

    if (confirmResult === 'confirm') {
      // 逐个删除
      let allSuccess = true;
      const pathsToDelete = [...selectedItems.value]; // 创建副本

      // 清空选中项
      selectedItems.value = [];

      // 逐个删除
      for (const item of pathsToDelete) {
        try {
          const response = await deleteDirApi(serverKey.value, item.path);
          if (response.code !== 0 || !response.data.success) {
            allSuccess = false;
            ElMessage.warning(`${item.name}: ${response.message || t('clusters.distributeFilePage.deleteFail')}`);
          }
        } catch (error) {
          allSuccess = false;
          console.error(`Failed to delete ${item.name}:`, error);
        }
      }

      // 重新加载列表
      await loadDirList(currentPath.value);

      if (allSuccess) {
        ElMessage.success(t('clusters.distributeFilePage.deleteSuccess', {
          itemType: itemType
        }));
      } else {
        ElMessage.warning(t('clusters.distributeFilePage.deleteFail'));
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('clusters.distributeFilePage.deleteFailedMsg'));
      console.error('Failed to batch delete:', error);
    }
  }
};

// 选择/取消选择项
const toggleItemSelection = (item: FileInfoModel, checked: boolean) => {
  const index = selectedItems.value.findIndex(i => i.path === item.path);
  if (checked && index === -1) {
    selectedItems.value.push(item);
  } else if (!checked && index > -1) {
    selectedItems.value.splice(index, 1);
  }
};

// 全选/取消全选
const toggleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedItems.value = [...fileList.value];
  } else {
    selectedItems.value = [];
  }
};

// 判断项是否被选中
const isItemSelected = (item: FileInfoModel): boolean => {
  return selectedItems.value.some(i => i.path === item.path);
};

// 判断是否全选
const isAllSelected = computed(() => {
  return fileList.value.length > 0 && selectedItems.value.length === fileList.value.length;
});

// 获取图标类名
const getIconClass = (isDir: boolean) => {
  return isDir ? 'el-icon-folder' : 'el-icon-file';
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <el-input
          disabled
          v-model="serverKey"
          :placeholder="t('clusters.distributeFilePage.serverKeyPlaceholder')"
          style="width: 240px; margin-right: 10px;"
        />
        <el-button type="primary" @click="loadDirList()"> {{ t('clusters.distributeFilePage.loadDir') }} </el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedItems.length === 0"
          style="margin-left: 10px;"
        >
          {{ t('clusters.distributeFilePage.batchDelete') }}
          <template #suffix>
            <span v-if="selectedItems.length > 0" class="selected-count">
              {{ t('clusters.distributeFilePage.selectedCount', { count: selectedItems.length }) }}
            </span>
          </template>
        </el-button>
      </div>
    </template>

    <!-- 文件管理区域 -->
    <div class="file-manager-container">
      <!-- 路径导航 -->
      <div class="path-navigator">
        <el-button
          type="text"
          @click="loadDirList('')"
          :class="{ 'active': currentPath === '' }"
          icon="el-icon-folder"
        >
          {{ t('clusters.distributeFilePage.rootDir') }}
        </el-button>
        <el-button
          v-if="pathHistory.length > 0"
          type="text"
          @click="goBack"
          icon="el-icon-back"
        >
          {{ t('clusters.distributeFilePage.back') }}
        </el-button>
      </div>

      <!-- 当前路径显示 -->
      <div class="current-path" v-if="currentPath">
        {{ t('clusters.distributeFilePage.currentPath') }}: {{ currentPath }}
      </div>

      <!-- 文件列表 -->
      <div class="file-list">
        <!-- 全选框 -->
        <div class="select-all-container" v-if="fileList.length > 0">
          <el-checkbox
            v-model="isAllSelected"
            @change="toggleSelectAll"
            style="margin-right: 10px;"
          >
            {{ t('clusters.distributeFilePage.selectAll') }}
          </el-checkbox>
          <span v-if="selectedItems.length > 0" class="selected-info">
            {{ t('clusters.distributeFilePage.selectedCount', { count: selectedItems.length }) }}
          </span>
        </div>

        <!-- 文件项 -->
        <div
          v-for="item in fileList"
          :key="item.path"
          class="file-item"
          @click="enterSubDir(item)"
        >
          <div class="file-checkbox">
            <el-checkbox
              :model-value="isItemSelected(item)"
              @change="(checked) => toggleItemSelection(item, checked)"
              @click.stop
            />
          </div>
          <div class="file-icon">
            <i :class="getIconClass(item.isDir)"></i>
          </div>
          <div class="file-info">
            <div class="file-name">{{ item.name }}</div>
            <div class="file-meta">
              {{ item.isDir ? t('clusters.distributeFilePage.directory') : t('clusters.distributeFilePage.file') }} ·
              {{ item.isDir ? '-' : formatFileSize(item.size) }} ·
              {{ t('clusters.distributeFilePage.modifyTime') }}: {{ item.modTime }}
            </div>
          </div>
          <div class="file-actions">
            <el-button
              type="text"
              size="small"
              @click.stop="handleDelete(item)"
              icon="el-icon-delete"
            >
              {{ t('clusters.distributeFilePage.delete') }}
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="!loading && fileList.length === 0">
          <el-empty :description="t('clusters.distributeFilePage.emptyState')" />
        </div>

        <!-- 加载状态 -->
        <div v-else-if="loading" class="loading-state">
          <el-skeleton animated :rows="3" />
        </div>
      </div>
    </div>
  </el-card>
</template>

<style scoped lang="scss">
.file-manager-container {
  padding: 20px 0;
}

.path-navigator {
  margin-bottom: 15px;
}

.current-path {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
  }
}

.file-checkbox {
  margin-right: 10px;
  flex-shrink: 0;
}

.select-all-container {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
}

.selected-info {
  color: #409eff;
  font-size: 14px;
}

.selected-count {
  margin-left: 5px;
  color: #409eff;
}

.loading-state {
  padding: 20px 0;
}

.card-header {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 12px;
  font-size: 20px;
  color: #409eff;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.file-meta {
  font-size: 12px;
  color: #909399;
}

.file-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.file-item:hover .file-actions {
  opacity: 1;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.active {
  color: #409eff !important;
  font-weight: 500;
}
</style>
